package cn.hxzy.commonUser.service.impl;

import cn.hxzy.commonUser.mapper.UserMapper;
import cn.hxzy.entity.userEntity.User;
import cn.hxzy.entity.userEntity.vo.LoginByCodeUser;
import cn.hxzy.entity.userEntity.vo.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;


/**
 * 实现认证管理器接口
 * 重写验证码校验规则
 */

@Service("CodeProvider")
public class AuthenticationProviderImpl implements AuthenticationProvider {

    @Autowired
    @Qualifier("redis")
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

      //得到手机号
        String phone = (String) authentication.getPrincipal();

        //通过手机号得到权限对象
        UserDetails userDetails = userDetailsService.loadUserByUsername(phone);
        if (userDetails == null)
            throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");

        //得到用户输入的验证码
        String code = (String) authentication.getCredentials();
        if (code.length()>4){ //若用户输入的是密码
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("user_phone",phone);
            User user = userMapper.selectOne(queryWrapper);
            if (!user.getUserPwd().equals(code))throw new InternalAuthenticationServiceException("密码输入有误");

        }else {   //若输入的是验证码
            //从redis中取到手机号对应的验证码
            String realCode = (String)redisTemplate.opsForValue().get(phone);
            if (!code.equals(realCode))throw new InternalAuthenticationServiceException("验证码输入有误");
        }
        SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());
        //存储有关身份验证请求的其他详细信息,可能是IP地址、证书序列号等
        authenticationResult.setDetails(authentication.getDetails());


        return authenticationResult;//返回验证码校验成功后的权限对象

    }

    @Override
    public boolean supports(Class<?> authentication) {
        return false;
    }


}
